package com.wlb365.financing.modules.sys.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlb365.financing.common.constants.ApiConstants;
import com.wlb365.financing.common.constants.SysConstant;
import com.wlb365.financing.common.exception.AdminException;
import com.wlb365.financing.common.support.controller.BaseController;
import com.wlb365.financing.common.dto.R;
import com.wlb365.financing.common.utils.ShiroUtil;
import com.wlb365.financing.common.utils.StringUtils;
import com.wlb365.financing.modules.sys.entity.Dept;
import com.wlb365.financing.modules.sys.entity.User;
import com.wlb365.financing.modules.sys.request.OrgBindingBankReq;
import com.wlb365.financing.modules.sys.request.OrgPageReq;
import com.wlb365.financing.modules.sys.response.OrgBindingBankVo;
import com.wlb365.financing.modules.sys.response.OrgPageVo;
import com.wlb365.financing.modules.sys.response.OrgRelationVo;
import com.wlb365.financing.modules.sys.service.IDeptService;
import com.wlb365.sdk.client.SdkClient;
import com.wlb365.sdk.model.CommonRequest;
import com.wlb365.sdk.model.CommonResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 概述：部门
 * </p>
 *
 * @author zwh
 * @version 1.0
 * @copyRight 北京微利宝信息技术有限公司  All right reserved.
 * @date 2020/3/21
 */
@RestController
@RequestMapping("sys/dept")
public class DeptController extends BaseController {

    @Autowired
    private IDeptService deptService;

    @Autowired
    private SdkClient sdkClient;

    @RequiresPermissions("sys:dept:index")
    @GetMapping("index")
    public ModelAndView index() {
        return new ModelAndView("sys/dept");
    }

    @RequiresPermissions("sys:dept:bankAndCore")
    @GetMapping("bankAndCore")
    public ModelAndView bankAndCore() {
        return new ModelAndView("sys/bank_and_core");
    }

    /**
     * 跳转关系维护界面
     * @param id 主键id 对应着sevice服务的主键id
     * @param comType 机构类型
     * @return
     */
    @RequiresPermissions("sys:dept:deptRelation")
    @GetMapping("deptRelation")
    public ModelAndView deptRelation(String id,String comType) {
        ModelAndView modelAndView = new ModelAndView("sys/dept_relation");
        modelAndView.addObject("id",id);
        modelAndView.addObject("comType",comType);
        return modelAndView;
    }

    /**
     * 跳转机构绑定银行列表界面
     * @return
     */
    @RequiresPermissions("sys:dept:deptBank")
    @GetMapping("deptBank")
    public ModelAndView deptBank(@RequestParam(name = "compId") String compId) {
        ModelAndView modelAndView = new ModelAndView("sys/dept_bank");
        modelAndView.addObject("compId",compId);
        return modelAndView;
    }

    /**
     * 机构关系维护列表
     * @param id 主键id
     * @param comType 机构类型
     * @return
     */
    @GetMapping(value = "deptRelation/data")
    public OrgRelationVo queryOrgRelation(
            String comType,
            String id){
        // 拿到所有机构列表
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_LIST);
        Map<String,Object> params = new HashMap<>();
        params.put("compIds",null);
        params.put("compType",comType);
        params.put("relationId",id);
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        OrgRelationVo orgRelationVo = JSONUtil.toBean(commonResponse.getData(), OrgRelationVo.class);
        return orgRelationVo;
    }

    /**
     * 机构关系关系全量
     * @param id 机构id
     * @param relationList 关联机构id数组
     * @return
     */
    @RequiresPermissions("sys:dept:deptRelationEdit")
    @PostMapping(value = "deptRelationEdit")
    @Transactional
    public R deptRelationEdit(@RequestParam(name = "id") String id,
                              @RequestParam(name = "relationList") List<String> relationList){
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_RELATION);
        Map<String,Object> params = new HashMap<>();
        params.put("compId",id);
        params.put("relation",relationList);
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        if(!commonResponse.getCode().equals(ApiConstants.SUCCESS_CODE)){
            throw new AdminException("服务端异常,维护关系失败");
        }
        return R.ok();
    }


    @GetMapping(value = "edit")
    public ModelAndView edit(String id) {
        ModelAndView mv = new ModelAndView("sys/dept_edit");
        Dept dept;
        if (id == null) {
            dept = new Dept();
        } else {
            dept = deptService.getById(id);
        }
        mv.addObject("editInfo", dept);
        return mv;
    }

    /**
     * 机构列表分页查询
     * @param dept
     * @return
     */
    @GetMapping(value = "list/data")
        public R listData(Dept dept) {
        // 不是平台管理员就查询自己的机构信息
        User user = ShiroUtil.getUser();
        if(!user.getUsername().equals(SysConstant.ADMIN)){
            dept.setId(user.getDeptId());
        }
        Page<Dept> page = deptService.listDeptPage(dept);
        return R.ok(page);
    }

    /**
     * 查询银行信息
     * @param dept
     * @return
     */
    @GetMapping(value = "list/bankData")
    public R listBankData(Dept dept) {
        Page<Dept> page = deptService.listDeptPage(dept);
        return R.ok(page);
    }

    @GetMapping(value = "list/tree")
    public R listTree(String parentId) {
        return R.ok(deptService.listDeptByParentId(parentId));
    }

    @RequiresPermissions("sys:dept:add")
    @PostMapping(value = "add")
    @Transactional
    public R add(Dept dept) {

        // web端新增
        deptService.save(dept);
        // 服务端新增
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_ADD);
        Map<String,Object> params = new HashMap<>();
        params.put("admCerNo",dept.getAdmCerNo());
        params.put("admMobPhone",dept.getAdmMobPhone());
        params.put("admName",dept.getAdmName());
        params.put("appId",dept.getAppId());
        params.put("busLicImageUrl",dept.getBusLicImageUrl());
        params.put("comAddress",dept.getComAddress());
        params.put("comCerNo",dept.getComCerNo());
        params.put("compName",dept.getName());
        params.put("compType",dept.getType());
        params.put("comId",dept.getComId());
        params.put("source",dept.getSource());
        params.put("id",dept.getId());
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);
        if(!commonResponse.getCode().equals(ApiConstants.SUCCESS_CODE)){
            throw new AdminException("服务端异常,新增机构失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(commonResponse.getData());
        String orgId = jsonObject.getString("id");
        dept.setId(orgId);

        return R.ok();
    }

    @RequiresPermissions("sys:dept:edit")
    @PostMapping(value = "edit")
    @Transactional
    public R edit(Dept dept) {
        // web修改
        deptService.updateById(dept);
        // 服务端修改
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_EDITBYID);
        Map<String,Object> params = new HashMap<>();
        params.put("admCerNo",dept.getAdmCerNo());
        params.put("admMobPhone",dept.getAdmMobPhone());
        params.put("admName",dept.getAdmName());
        params.put("appId",dept.getAppId());
        params.put("busLicImageUrl",dept.getBusLicImageUrl());
        params.put("comAddress",dept.getComAddress());
        params.put("comCerNo",dept.getComCerNo());
        params.put("compName",dept.getName());
        params.put("id",dept.getId());
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);;
        if(!commonResponse.getCode().equals(ApiConstants.SUCCESS_CODE)){
            throw new AdminException("服务端异常,修改机构失败");
        }
        return R.ok();
    }

    /**
     * 根据id删除机构
     * @param ids    web端机构主键id集合
     * @return
     */
    @RequiresPermissions("sys:dept:del")
    @PostMapping(value = "remove")
    @Transactional
    public R remove(@RequestParam("ids") List<String> ids) {
        deptService.removeByIds(ids);
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_DELETE);
        Map<String,Object> params = new HashMap<>();
        params.put("ids",ids);
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);;
        if(!commonResponse.getCode().equals(ApiConstants.SUCCESS_CODE)){
            throw new AdminException("服务端异常,删除机构失败");
        }
        return R.ok();
    }

    @GetMapping(value = "get/{id}")
    public R get(@PathVariable String id) {
        return R.ok(deptService.getById(id));
    }


    /**
     * 调用service服务的机构分页列表接口
     * @return
     */
    @GetMapping("listServer/data")
    public OrgPageVo deptRelation(OrgPageReq orgPageReq) {
        CommonRequest commonRequest = new CommonRequest(ApiConstants.FS_CUSTOMER_ORG_PAGE);
        Map<String,Object> params = new HashMap<>();
        params.put("comId",orgPageReq.getCompId());
        params.put("compType",orgPageReq.getCompType());
        params.put("compName",orgPageReq.getCompName());
        params.put("current",orgPageReq.getCurrent());
        params.put("size",orgPageReq.getSize());
        commonRequest.setBizModel(params);
        CommonResponse commonResponse =  sdkClient.execute(commonRequest);;
        OrgPageVo orgPageVo = JSONUtil.toBean(commonResponse.getData(),OrgPageVo.class);
        return orgPageVo;
    }
}

